package com.magicalcoder.pigeontest.server.init;

import com.magicalcoder.pigeon.ioc.BeanFactory;
import com.magicalcoder.pigeon.ioc.PigeonBeanContainer;
import com.magicalcoder.pigeon.mysql.manager.ConnectionManager;
import com.magicalcoder.pigeon.mysql.manager.dto.JdbcProperties;
import com.magicalcoder.pigeontest.service.impl.ConnectionManagerTemplate;
import com.magicalcoder.pigeontest.service.impl.ConnectionManagerTemplateImpl;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by hzhedongyu on 2017/6/15.
 */
public class InitStart {

    private BeanFactory beanFactory = new BeanFactory();
    public void init(){
        ioc();
        jdbc();
    }

    private void ioc(){
        try {
            beanFactory.scanAllBeans("com.magicalcoder.pigeontest.service.impl");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private void jdbc(){
        InputStream inputStream = InitStart.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        JdbcProperties jdbcProperties = new JdbcProperties();
        try {
            if(inputStream!=null){
                properties.load(inputStream);
            }
            jdbcProperties.setDriverClass(properties.getProperty("jdbc.driverClass","com.mysql.cj.jdbc.Driver"));
            jdbcProperties.setCoreSize(Integer.valueOf(properties.getProperty("jdbc.coreSize","1")));
            jdbcProperties.setMaximumPoolSize(Integer.valueOf(properties.getProperty("jdbc.maximumPoolSize","2")));
            jdbcProperties.setKeepAliveTime(Integer.valueOf(properties.getProperty("jdbc.keepAliveTime","30000")));
            jdbcProperties.setUser(properties.getProperty("jdbc.user","root"));
            jdbcProperties.setPassword(properties.getProperty("jdbc.password",""));
            jdbcProperties.setWaitTimeout(Integer.valueOf(properties.getProperty("jdbc.waitTimeout","15000")));
            jdbcProperties.setUrl(properties.getProperty("jdbc.url","jdbc:mysql://localhost:3306/youyamvc?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        ConnectionManager connectionManager = new ConnectionManager(jdbcProperties);
        /*DbConnection dbConnection = connectionManager.acquireCon();
        Execute executeSql = new ExecuteSql(dbConnection);*/
        ConnectionManagerTemplate connectionManagerTemplate = PigeonBeanContainer.getBean(ConnectionManagerTemplateImpl.class);
        connectionManagerTemplate.setConnectionManager(connectionManager);
    }

}
